<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'
import {CirclePlus, GoodsFilled, Refresh, Search} from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const addDialogVisible = ref(false)

// 添加表单数据
const addForm = ref({
  id: '',
  name: '',
  typeId: '',
  storageId: '',
  count: '',
  remark: ''
})
// 打开添加对话框
const handleAdd = () => {
  addForm.value = {
    id: '',
    name: '',
    typeId: '',
    storageId: '',
    count: '',
    remark: ''
  }
  addDialogVisible.value = true
}
// 提交新增
const submitAdd = async () => {
  try {
    // 基础验证
    if (!addForm.value.name.trim()) {
      ElMessage.warning('货物名称未填写')
      return
    }

    const response = await axios.post('http://localhost:8080/goods/save', {
      ...addForm.value
    })

    if (response.data) {
      ElMessage.success('新增成功')
      addDialogVisible.value = false
      await fetchUsers() // 刷新数据
    }
  } catch (error) {
    ElMessage.error('新增失败')
    console.error('新增错误:', error)
  }
}
// 编辑表单数据
const editForm = ref({
  id: '',
  name: '',
  typeId: '',
  storageId: '',
  count: '',
  remark: ''
})
// 编辑操作
const handleEdit = (row) => {
  editForm.value = { ...row }
  dialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    const response = await axios.put('http://localhost:8080/goods/update', editForm.value)
    if (response.data) {
      ElMessage.success('修改成功')
      dialogVisible.value = false
      await fetchUsers() // 刷新数据
    }
  } catch (error) {
    ElMessage.error('修改失败')
    console.error('更新错误:', error)
  }
}
// 删除操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除货物 ${row.name} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.delete('http://localhost:8080/goods/delete', {
      params: { id: row.id }
    })

    if (response.data) {
      ElMessage.success('删除成功')
      await fetchUsers() // 刷新数据
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除错误:', error)
    }
  }
}
// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 查询参数
const queryParams = ref({
  name: '',
  typeId: '',
  storageId: ''
})

// 获取用户数据
const fetchUsers = async () => {
  loading.value = true
  try {
    const requestParams = {
      name: queryParams.value.name,
      typeId: queryParams.value.typeId ? Number(queryParams.value.typeId) : null,
      storageId: queryParams.value.storageId ? Number(queryParams.value.storageId) : null
    }

    const response = await axios.post('http://localhost:8080/goods/listPage', {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      param: requestParams
    })

    tableData.value = response.data.data
    pagination.value.total = response.data.total
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  pagination.value.pageNum = 1
  fetchUsers()
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    name: '',
    typeId: '',
    storageId: ''
  }
  handleQuery()
}

// 分页变化
const handlePageChange = (newPage) => {
  pagination.value.pageNum = newPage
  fetchUsers()
}

// 获取仓库列表--转换仓库id为对应仓库名
const storageList = ref([])
// 获取货物类型列表--转换货物类型id为对应货物类型名
const goodsTypeList = ref([])

// 获取货物类型列表
const fetchGoodsTypes = async () => {
  try {
    const response = await axios.post('http://localhost:8080/goodsType/list')
    goodsTypeList.value = response.data.data
  } catch (error) {
    ElMessage.error('货物类型数据加载失败')
    console.error('获取货物类型列表失败:', error)
  }
}

// 获取仓库列表
const fetchStorages = async () => {
  try {
    const response = await axios.post('http://localhost:8080/storage/list')
    storageList.value = response.data.data
  } catch (error) {
    ElMessage.error('仓库数据加载失败')
    console.error('获取仓库列表失败:', error)
  }
}
const currentUser = ref(null)
// 初始化时获取
onMounted(() => {
  // 从localStorage获取当前登录用户
  const userData = localStorage.getItem('user')
  if(userData) {
    currentUser.value = JSON.parse(userData)
  }
  fetchUsers()
  fetchStorages()
  fetchGoodsTypes()
})

const idToTypeName = (id) => {
  const found = goodsTypeList.value.find(item => item.id === id)
  return found ? found.name : '未知类型'
}
const idToName = (id) => {
  const found = storageList.value.find(item => item.id === id)
  return found ? found.name : '未知仓库'
}
// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(pagination.value.total / pagination.value.pageSize)
})

// 出入库操作
// 添加用户选择对话框相关状态
const userDialogVisible = ref(false);
const selectedUser = ref(null); // 存储选中的用户
const userTableData = ref([]); // 用户列表数据
// 获取用户列表（过滤普通用户 roleId=2）
const fetchUsersForSelect = async () => {
  try {
    const response = await axios.post('http://localhost:8080/user/listPage', {
      pageNum: 1,
      pageSize: 1000,
      param: { roleId: 2 } // 只查询普通用户
    });
    console.log('用户列表数据:', response.data)
    userTableData.value = response.data.data;
    pagination.value.total = response.data.total;
  } catch (error) {
    ElMessage.error('用户数据加载失败');
  }
};
// 用户表格行点击事件
const handleUserRowClick = (row) => {
  selectedUser.value = row;
};
// 用户表格行高亮样式
const userTableRowClassName = ({ row }) => {
  return row.id === selectedUser.value?.id ? 'highlight-row' : '';
};
// 确认选择用户
const confirmUserSelect = () => {
  if (!selectedUser.value) {
    ElMessage.warning('请先选择用户');
    return;
  }
  stockInForm.value.userId = selectedUser.value.id; // 绑定到入库表单
  stockOutForm.value.userId = selectedUser.value.id; // 绑定到出库表单
  userDialogVisible.value = false;
};
// 新增当前操作商品存储
const currentGoods = ref(null);
// 添加入库表单数据
const stockInForm = ref({
  count: 0,
  remark: ''
});
const stockInDialogVisible = ref(false);
// 打开入库对话框
const handleStockIn = (row) => {
  stockInForm.value = {
    count: 0,
    remark: ''
  };
  currentGoods.value = row; // 新增当前操作商品存储
  stockInDialogVisible.value = true;
};


// 添加出库表单数据
const stockOutForm = ref({
  count: 0,
  remark: ''
});
const stockOutDialogVisible = ref(false);
// 打开入库对话框
const handleStockOut = (row) => {
  stockOutForm.value = {
    count: 0,
    remark: ''
  };
  currentGoods.value = row; // 新增当前操作商品存储
  stockOutDialogVisible.value = true;
};
// 提交入库
const submitStockIn = async () => {
  try {
    // 从localStorage获取当前登录用户（假设登录时存储了用户信息）
    const currentUser = JSON.parse(localStorage.getItem('user'));

    // 参数校验
    if (!stockInForm.value.userId) {
      ElMessage.warning('请选择申请人');
      return;
    }
    if (stockInForm.value.count <= 0) {
      ElMessage.warning('入库数量必须大于0');
      return;
    }
    const response = await axios.post('http://localhost:8080/record/save', {
      goodsId: currentGoods.value.id,
      count: stockInForm.value.count,
      remark: stockInForm.value.remark,
      userId: stockInForm.value.userId,
      adminId: currentUser.id// 当前操作人的ID
    });

    if (response.data) {
      ElMessage.success('入库成功');
      stockInDialogVisible.value = false;
      await fetchUsers(); // 刷新数据
    }
  } catch (error) {
    ElMessage.error('入库失败');
    console.error('入库错误:', error);
  }
};
// 添加独立的出库提交方法
const submitStockOut = async () => {
  try {
    // 从localStorage获取当前登录用户（假设登录时存储了用户信息）
    const currentUser = JSON.parse(localStorage.getItem('user'));

    // 参数校验
    if (!stockOutForm.value.userId) {
      ElMessage.warning('请选择申请人');
      return;
    }
    if (stockOutForm.value.count <= 0) {
      ElMessage.warning('出库数量必须大于0');
      return;
    }

    const response = await axios.post('http://localhost:8080/record/save', {
      goodsId: currentGoods.value.id,
      count: -stockOutForm.value.count, // 传递负数
      remark: stockOutForm.value.remark,
      userId: stockOutForm.value.userId,
      adminId: currentUser.id
    });

    if (response.data) {
      ElMessage.success('出库成功');
      stockOutDialogVisible.value = false;
      await fetchUsers(); // 强制刷新数据
    }
  } catch (error) {
    ElMessage.error('出库失败');
    console.error('出库错误:', error);
  }
};
const selectedUserName = computed(() => selectedUser.value?.name || '');
const openUserSelectDialog = () => {
  userDialogVisible.value = true
  fetchUsersForSelect() // 添加数据获取
}

</script>

<template>
  <el-main class="main-content">
    <el-scrollbar>
      <!-- 查询表单 -->
      <div class="query-form">
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="货物名">
            <el-input
                v-model.trim="queryParams.name"
                placeholder="请输入货物名"
                clearable
                @keyup.enter="handleQuery"
                class="search-input"
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <GoodsFilled />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="货物类型">
            <el-select
                v-model="queryParams.typeId"
                placeholder="请选择类型"
                clearable
                filterable
                class="search-select"
            >
              <el-option
                  v-for="item in goodsTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="所属仓库">
            <el-select
                v-model="queryParams.storageId"
                placeholder="请选择仓库"
                clearable
                filterable
                class="search-select"
            >
              <el-option
                  v-for="item in storageList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="action-buttons">
            <el-button
                type="primary"
                :loading="loading"
                @click="handleQuery"
                class="query-btn"
            >
              <el-icon class="mr-1"><Search /></el-icon>
              查询
            </el-button>
            <el-button
                @click="resetQuery"
                class="reset-btn"
            >
              <el-icon class="mr-1"><Refresh /></el-icon>
              重置
            </el-button>
            <el-button
                type="success"
                :loading="loading"
                @click="handleAdd"
                class="add-btn"
                v-if="currentUser?.roleId !== 2"
            >
              <el-icon class="mr-1"><CirclePlus /></el-icon>
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
          :data="tableData"
          height="calc(100vh - 120px)"
          v-loading="loading"
          class="data-table"
      >
        <!-- 表格列定义 -->
        <el-table-column label="序号" width="80" type="index">
          <template #default="{ $index }">
            {{ (pagination.pageNum - 1) * pagination.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="140" v-if="false" /><!--隐藏-->
        <el-table-column prop="name" label="货物名" width="180" />
        <el-table-column prop="typeId" label="类型编号" width="180" >
          <template #default="{row}">
            {{ idToTypeName(row.typeId) }}
          </template>
        </el-table-column>
        <el-table-column prop="storageId" label="仓库名" width="120">
          <template #default="{row}">
            {{ idToName(row.storageId) }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="数量" width="120" />
        <el-table-column prop="remark" label="备注" width="400" itemtype="text" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)"  v-if="currentUser?.roleId !== 2">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)"  v-if="currentUser?.roleId !== 2">删除</el-button>
            <el-button type="warning" size="small" @click="handleStockIn(row)">入库</el-button>
            <el-button type="success" size="small" @click="handleStockOut(row)">出库</el-button>
          </template>
        </el-table-column>

        <!-- 分页 -->
        <template #append>
          <div class="pagination-wrapper" style="display: flex; align-items: center; gap: 16px;">
            <div class="pagination-info">
              共 {{ pagination.total }} 条，第 {{ pagination.pageNum }}/{{ totalPages }} 页
            </div>
            <el-pagination
                :current-page="pagination.pageNum"
                :page-size="pagination.pageSize"
                :total="pagination.total"
                layout="prev, pager, next, ->, slot"
                @current-change="handlePageChange"
                class="custom-pagination single-page-pager"
                style="margin-top: 10px"
            >
              <div class="page-controls" style="display: flex; align-items: center; gap: 8px; ">
                <span class="current-page">跳转到</span>
                <el-select
                    v-model="pagination.pageNum"
                    placeholder="跳转至"
                    size="small"        style="width: 110px; margin-left: 10px"
                    @change="handlePageChange"
                >
                  <el-option
                      v-for="n in totalPages"
                      :key="n"
                      :label="`第 ${n} 页`"
                      :value="n"
                      style="text-align: center"
                  />
                </el-select>
              </div>
            </el-pagination>
          </div>
        </template>
      </el-table>
      <!-- 用户选择对话框 -->
      <el-dialog v-model="userDialogVisible" title="选择申请人" width="70%">
        <el-table
            :data="userTableData"
            height="400"
            @row-click="handleUserRowClick"
            :row-class-name="userTableRowClassName"
        >
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="no" label="账号" width="180" />
          <el-table-column prop="sex" label="性别" width="120" />
          <el-table-column prop="age" label="年龄" width="120" />
          <el-table-column prop="phone" label="电话" width="180" />
          <el-table-column prop="roleId" label="身份" width="150">
            <template #default="{ row }">
              <el-tag
                  :type="{
                0: 'danger',
                1: 'warning',
                2: 'success'
              }[row.roleId]"
                  effect="dark"
              >
                {{ ['超级管理员', '管理员', '用户'][row.roleId] || '未知身份' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUserSelect">确认</el-button>
        </template>
      </el-dialog>
      <!-- 入库对话框 -->
      <el-dialog v-model="stockInDialogVisible" title="货物入库" width="35%">
        <el-form :model="stockInForm" label-width="100px">
          <el-form-item label="申请人">
            <el-input
                :model-value="selectedUserName"
                readonly
                placeholder="点击选择申请人"
                @click="openUserSelectDialog"


            />
          </el-form-item>
          <el-form-item label="入库数量" required>
            <el-input-number
                v-model="stockInForm.count"
                :min="1"
                controls-position="right"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="stockInForm.remark" type="textarea" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="stockInDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStockIn">确认</el-button>
        </template>
      </el-dialog>
      <!-- 出库对话框 -->
      <el-dialog v-model="stockOutDialogVisible" title="货物出库" width="35%">
        <el-form :model="stockOutForm" label-width="100px">
          <el-form-item label="申请人">
            <el-input
                :model-value="selectedUserName"
                readonly
                placeholder="点击选择申请人"
                @click="openUserSelectDialog"
            />
          </el-form-item>
          <el-form-item label="出库数量" required>
            <el-input-number
                v-model="stockOutForm.count"
                :min="1"
                controls-position="right"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="stockOutForm.remark" type="textarea" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="stockOutDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStockOut">确认</el-button>
        </template>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogVisible" title="货物编辑" width="35%">
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="货物名">
            <el-input v-model="editForm.name" clearable />
          </el-form-item>
          <el-form-item label="类型">
            <el-select
                v-model="editForm.typeId"
                placeholder="请选择类型"
                filterable
                clearable
            >
              <el-option
                  v-for="item in goodsTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库">
            <el-select
                v-model="editForm.storageId"
                placeholder="请选择仓库"
                filterable
                clearable
            >
              <el-option
                  v-for="item in storageList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数量">
            <el-input v-model="editForm.count" clearable />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="editForm.remark" type="textarea" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确认</el-button>
        </template>
      </el-dialog>

      <!-- 新增用户对话框 -->
      <el-dialog v-model="addDialogVisible" title="新增用户" width="35%">
        <el-form :model="addForm" label-width="80px">
          <el-form-item label="货物名" required>
            <el-input v-model.trim="addForm.name" clearable />
          </el-form-item>
          <el-form-item label="货物类型" required>
            <el-select
                v-model="addForm.typeId"
                placeholder="请选择类型"
                clearable
                filterable
            >
              <el-option
                  v-for="item in goodsTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="所属仓库" required>
            <el-select
                v-model="addForm.storageId"
                placeholder="请选择仓库"
                clearable
                filterable
            >
              <el-option
                  v-for="item in storageList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数量" required>
            <el-input v-model.number="addForm.count" clearable />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="addForm.remark" type="textarea" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">确认</el-button>
        </template>
      </el-dialog>
    </el-scrollbar>
  </el-main>
</template>

<style scoped>
/* 主内容区 */
.main-content {
  padding: 0 !important;
  background: #f8fafc;
}

/* 查询表单 */
.query-form {
  padding: 16px 24px;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

/* 输入框样式 */
.search-input {
  width: 240px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06) !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
}

.input-icon {
  color: #64748b;
  margin-right: 8px;
}

/* 操作按钮 */
.action-buttons {
  margin-left: auto;
}

.query-btn,
.reset-btn {
  padding: 8px 20px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.query-btn:hover {
  background-color: var(--el-color-primary); /* 使用主题颜色 */
  border-color: var(--el-color-primary); /* 使用主题颜色 */
}

.el-button--primary:hover {
  background-color: var(--el-color-primary); /* 使用主题颜色 */
  border-color: var(--el-color-primary); /* 使用主题颜色 */
}

.reset-btn:hover {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

/* 数据表格 */
.data-table {
  margin: 0 16px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header th) {
  background-color: #f8fafc !important;
  font-weight: 600;
}
/* 对话框动画 */
.el-dialog {
  transition: all 0.3s ease-out;
}

/* 新增按钮样式 */
.add-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;

  &:hover {
    background-color: #5daf34;
    border-color: #5daf34;
  }
}
.pagination-info {
  margin-left: 16px;
  font-size: 14px;
  margin-top: 10px;
}
:deep(.el-table .highlight-row) {
  background-color: #8bd7e8 !important;
}
</style>
